package com.dbflow5.models;

import com.dbflow5.TestDatabase;
import com.dbflow5.config.FlowManager;
import com.dbflow5.query.SQLite;

import com.dbflow5.BaseUnitTest;
import com.dbflow5.structure.Model;
import org.junit.Assert;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.assertNotEquals;

public class CachingModelsTest extends BaseUnitTest {
    @Test
    public void testSimpleCache() {
        FlowManager.database(TestDatabase.class, testDatabase -> {
            List<CachingModels.SimpleCacheObject> list = new ArrayList<>();
            for (int i = 0; i < 10; i++) {
                CachingModels.SimpleCacheObject simpleCacheObject = new CachingModels.SimpleCacheObject(String.valueOf(i));
                Model.save(CachingModels.SimpleCacheObject.class, simpleCacheObject, testDatabase);
                list.add(simpleCacheObject);
            }
            List<CachingModels.SimpleCacheObject> loadedList = SQLite.select().from(CachingModels.SimpleCacheObject.class).queryList(testDatabase);
            for (int i = 0; i < loadedList.size(); i++) {
                Assert.assertEquals(list.get(i), loadedList.get(i));
            }
            return null;
        });
    }

    @Test
    public void testComplexObject() {
        FlowManager.database(TestDatabase.class, testDatabase -> {
            CachingModels.Path path = new CachingModels.Path("1", "Path");
            Model.save(CachingModels.Path.class, path, testDatabase);

            CachingModels.Coordinate coordinate = new CachingModels.Coordinate(40.5, 84.0, path);
            Model.save(CachingModels.Coordinate.class, coordinate, testDatabase);

            CachingModels.Path oldPath = coordinate.path;
            CachingModels.Coordinate loadedCoordinate = SQLite.select().from(CachingModels.Coordinate.class).querySingle(testDatabase);
            Assert.assertEquals(coordinate, loadedCoordinate);

            // we want to ensure relationships reloaded.
            assertNotEquals(oldPath, loadedCoordinate.path);
            return null;
        });
    }
}
